import { Component } from 'react'
import { View, Image, Checkbox, CheckboxGroup } from '@tarojs/components'
import { AtForm, AtInput, AtButton } from 'taro-ui'
import { SpTimer, SpToast, SpTab } from '@/components'
import Taro from '@tarojs/taro'
import { getThemeStyle, validate, showToast } from '@/utils'
import { navigationToReg, setToken, setTokenAndRedirect, addListener } from '../util'
import { connect } from 'react-redux'
import api from '@/api'
import './index.scss'
import { updateUserInfo } from '@/store/user'

const shangjialogo = require('@/assets/imgs/shangjialogo.jpg')
const dianpulogo = require('@/assets/imgs/applogo.png')
const TAB_LIST = [
  { value: 'merchant', label: '商家登录', text: '我已阅读了解米米商家', logo: shangjialogo },
  { value: 'distributor', label: '店铺登录', text: '我已阅读了解米米店铺', logo: dianpulogo },
]

@connect(({ planSelection, user }) => ({
  planSelection,
  userinfo: user.userInfo
}),
  (dispatch) => ({ dispatch })
)
export default class Login extends Component {
  state = {
    info: {
      mobile: '',
      code: '',
      password: '',
      checked: false,
    },
    checkboxText: '我已阅读了解米米店铺',
    logintype: 'distributor',
    loginLogo: dianpulogo,
  }

  componentDidMount() { }

  async handleSubmit() {
    const { mobile, code, password, checked } = this.state.info
    const { logintype } = this.state
    if (!checked) {
      showToast('请阅读并勾选协议')
      return
    }
    console.log(checked)
    if (!validate.isRequired(mobile)) {
      showToast('请输入您的账号')
      return
    }
    // if (!validate.isRequired(code)) {
    //   showToast('请输入验证码')
    //   return
    // }
    console.log(password)
    console.log(validate.isRequired(password))
    if (!validate.isRequired(password)) {
      showToast('请输入密码')
      return
    }
    // if (!validate.isPassword(password)) {
    //   return showToast('密码格式不正确')
    // }
    const { token } = await api.operator.operatorLogin({
      username: mobile,
      password: password,
      logintype: logintype,
      product_model: 'platform'
    })
    console.log(token)

    // if (logintype == 'merchant') {
    //   setToken(token, 0)
    //   await this.getMyInfoHandle()
    //   // Taro.redirectTo({ url: `/pages/index` })
    // } else {
      setToken(token, 1)
      await this.getMyInfoHandle()

    // }
    // Taro.redirectTo({ url: `/pages/index` })
  }
  async getMyInfoHandle() {
    const obj = {
      is_app: 1
    }
    const result = await api.my.getMyinfo(obj)
    console.log(result)
    const { distributors } = result
    if (this.state.logintype == 'distributor') {
      // distributors && this.format_distributors(distributors)
      Taro.redirectTo({ url: `/pages/planSelection/index` })
    } else {
      let user = {}
      user.memberInfo = result
      const merchant = await api.shop.getEnterpriseInfo()
      user.memberInfo = {
        ...result,
        ...merchant
      }
      await this.props.dispatch(updateUserInfo(user))
      Taro.redirectTo({ url: `/pages/index` })
    }
  }
  format_distributors(data) {
    // const { dispatch } = this.props
    // const { activeShop } = this.props.planSelection
    // console.log(this.props.userinfo)
    // if (activeShop) {
    //   let { distributor_id } = activeShop
    //   console.log(distributor_id)
    //   const result = data.filter((item) => {
    //     return item.distributor_id == distributor_id
    //   })
    //   this.setState(
    //     {
    //       distributors: result[0]
    //     },
    //     () => {
    //       console.log(this.state.distributors)
    //       let user = {}
    //       let sss = {
    //         'logintype': this.state.logintype,
    //         'username': this.state.username,
    //         'head_portrait': this.state.head_portrait,

    //       }
    //       user.memberInfo = {
    //         ...sss,
    //         ...this.state.distributors
    //       }
    //       dispatch(updateUserInfo(user))
    //       Taro.redirectTo({ url: `/pages/planSelection/index` })
    //     }
    //   )
    // }
  }

  handleTimerStart = async (resolve) => {
    const { mobile } = this.state.info
    if (!validate.isMobileNum(mobile)) {
      showToast('请输入正确的手机号')
      return
    }
    await api.operator.sendCode({
      mobile
    })
    showToast('验证码已发送')
    resolve()
  }

  handleTimerStop() { }

  handleInputChange(name, val) {
    const { info } = this.state
    info[name] = val
    this.setState({
      info
    })
  }
  //点击tab
  handleChangeTab =  (active) => {
    console.log('点击了tab', TAB_LIST[active].value)
     this.setState({
      logintype: TAB_LIST[active].value,
      checkboxText: TAB_LIST[active].text,
      loginLogo: TAB_LIST[active].logo
    })
    console.log(this.state.checkboxText, this.state.logintype)
  }
  render() {
    const { info, checkboxText, loginLogo } = this.state
    return (
      <View className='page-auth-login' style={getThemeStyle()}>
        <View className='auth-hd'>
          <Image
            style='width: 100px;height: 100px;background: #fff;'
            src={loginLogo}
          />
        </View>

        <View className='auth-bd'>
          {/* <View className='form-title'>中国大陆 +86</View> */}
          {/* <View className='header'>
            <SpTab dataSource={TAB_LIST} onChange={this.handleChangeTab} />
          </View> */}
          <AtForm className='form'>
            <View className='form-field'>
              <AtInput
                className='auth-input'
                clear
                title='账号'
                name='mobile'
                value={info.mobile}
                placeholder='请输入您的账号'
                onChange={this.handleInputChange.bind(this, 'mobile')}
              />
            </View>
            <View className='form-field'>
              <View className='input-field'>
                <AtInput
                  className='auth-input'
                  clear
                  title='密码'
                  name='password'
                  // maxLength={11}
                  type='password'
                  value={info.password}
                  placeholder='请输入您的密码'
                  onChange={this.handleInputChange.bind(this, 'password')}
                />
              </View>
            </View>
            <View className='form-checkbox'>
              <CheckboxGroup onChange={({ detail }) => {
                console.log(detail)
                // this.setState()
                info.checked = detail.value.length > 0
              }}>
                <Checkbox value='ischecked' checked={info.checked}></Checkbox>
              </CheckboxGroup>
              {checkboxText}
              <a className='form-a' onClick={()=>{
                 Taro.navigateTo({ url: `pages/auth/xieyiWeb?type=fuwu` })
              }}>《服务协议》</a>
              <a className='form-a'  onClick={()=>{
                 Taro.navigateTo({ url: `pages/auth/xieyiWeb?type=yinsi` })
              }}> 《隐私政策》</a>
            </View>
            <View className='form-submit'>
              <AtButton
                circle
                className='btn-submit'
                type='primary'
                onClick={this.handleSubmit.bind(this)}
              >
                登录
              </AtButton>
            </View>
          </AtForm>
        </View>
        <SpToast />
      </View>
    )
  }
}
